package cn.csg.ams.collect2.poptopics.infrastructure.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * redis分布式锁
 */
@Component
public class RedisLockUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 加锁
     *
     * @param key     锁的key
     * @param value   锁的value
     * @param timeout 锁的超时时间
     * @return 是否加锁成功
     */
    public boolean lock(String key, String value, long timeout) {
        String script = "if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then redis.call('pexpire', KEYS[1], ARGV[2]) return 1 else return 0 end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(key), value, String.valueOf(timeout));
        return result != null && result == 1;
    }


    /**
     * 释放锁
     *
     * @param key   锁的key
     * @param value 锁的value
     * @return 是否释放锁成功
     */
    public boolean unlock(String key, String value) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(key), value);
        return result != null && result == 1;
    }

}
